<template>
  <div>
    <!-- 新增老人 -->
    <el-card class="card">
      <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="first">
          <BasicInfo></BasicInfo>
        </el-tab-pane>
        <el-tab-pane label="健康信息" name="second">
          <HealthInfo></HealthInfo>
        </el-tab-pane>
        <el-tab-pane label="家属信息" name="third">
          <FamilyInfo></FamilyInfo>
        </el-tab-pane>
      </el-tabs>
      <div style="text-align: center;margin-top: 20px">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save(ruleFormRef)">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, provide } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { FormInstance, FormRules, TabsPaneContext } from 'element-plus'
import BasicInfo from '../../components/market/elderly/add/BasicInfo.vue';
import HealthInfo from '../../components/market/elderly/add/HealthInfo.vue';
import FamilyInfo from '../../components/market/elderly/add/FamilyInfo.vue';
import { AddParams } from '@/api/market/elderly/type';
import { addElderly, getCheckupitems, getElderlyModel, getSelfcareList, updateElderly } from '@/api/market/elderly/elderly';

const activeName = ref('first')
const router = useRouter();
const route = useRoute();


//提供ref
const ruleFormRef = ref();
provide('ruleFormRef', ruleFormRef);

//添加参数
const ruleForm = reactive<AddParams>({
  name: "",
  mobile: "",
  photo: "",
  gender: 1,
  birthday: "",
  nativePlace: "",
  nation: "",
  idCard: "",
  politics: "",
  socialCard: "",
  marriage: "",
  eduLevel: "",
  education: "",
  resident: "",
  address: "",
  health: {

  },
  checkupList: [],
  selfCares: [],
  checkups: [],
  family: []
});


//规则
const rules = reactive<FormRules<AddParams>>({
  name: [{ required: true, message: "请输入老人姓名", trigger: "blur" }],
  gender: [
    {
      required: true, message: '请选择性别', trigger: 'change',
    },
  ],
  birthday: [
    {
      required: true, message: '请选择出生日期', trigger: 'change',
    },
  ],
  nativePlace: [
    {
      required: true, message: '请选择籍贯', trigger: 'change',
    },
  ],
  nation: [
    {
      required: true, message: '请选择民族', trigger: 'change',
    },
  ],
  idCard: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
  politics: [
    {
      required: true, message: '请选择政治面貌', trigger: 'change',
    },
  ],
  socialCard: [{ required: true, message: "请输入社保卡号", trigger: "blur" }],
  marriage: [
    {
      required: true, message: '请选择婚姻状况', trigger: 'change',
    },
  ],
  eduLevel: [
    {
      required: true, message: '请选择受教育程度', trigger: 'change',
    },
  ],
  education: [
    {
      required: true, message: '请选择最高学历', trigger: 'change',
    },
  ],
  resident: [{ required: true, message: "请输入户口所在地", trigger: "blur" }],
  address: [{ required: true, message: "请输入现居地址", trigger: "blur" }],
});
//提供规则
provide('rules', rules)

//提供添加参数
provide("ruleForm", ruleForm)

//取消
const cancel = () => {
  //跳转到老人列表
  router.push('/market/elderly')
}
//保存
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      ruleForm.health.oldillness = ruleForm.health.oldillnessArr?.join(",");
      ruleForm.health.nowillness = ruleForm.health.nowillnessArr?.join(",");

      if (route.params.id) {
        //修改
        await updateElderly(ruleForm);
      } else {
        //添加
        await addElderly(ruleForm);
      }
      //跳转到老人列表
      router.push('/market/elderly')
    } else {
      ElMessage.error('请完善基本信息')
    }
  })
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab, event)
}

//获取老人详情
const getElderlyDetail =  (id: number) => {

Promise.all([getElderlyModel(id),getCheckupitems(),getSelfcareList()]).then((res)=>{

  Object.assign(ruleForm, res[0]);
  ruleForm.health.nowillnessArr = ruleForm.health.nowillness?.split(',') || []
  ruleForm.health.oldillnessArr = ruleForm.health.oldillness?.split(',') || []

  ruleForm.checkupList = res[1].list.map(item => ({ ...item, checkups: ruleForm.checkups.filter(sItem => item.name == sItem.name) }));
  ruleForm.selfCares = res[2].list.filter(item => ruleForm.selfCares.filter(sItem => item.name == sItem.name ? item.val = sItem.val! : ""))

 
},fail=>{
  console.log('数据请求失败');
  
})

  // let res = await getElderlyModel(id);
  // console.log("res99", res);

  // Object.assign(ruleForm, res);
  // ruleForm.health.nowillnessArr = ruleForm.health.nowillness?.split(',') || []
  // ruleForm.health.oldillnessArr = ruleForm.health.oldillness?.split(',') || []

  //获取体检项目列表
  // let CheckupRes = await getCheckupitems();
  // ruleForm.checkupList = CheckupRes.list.map(item => ({ ...item, checkups: ruleForm.checkups.filter(sItem => item.name == sItem.name) }));

  //获取老人自理科目
  // let selfcareRes = await getSelfcareList();
  // ruleForm.selfCares = selfcareRes.list.filter(item => ruleForm.selfCares.filter(sItem => item.name == sItem.name ? item.val = sItem.val! : ""))


}

onMounted(async () => {
  if (route.params.id) {
    //调用老人详情
    getElderlyDetail(Number(route.params.id));
  }
})

</script>

<style scoped>
.card {
  width: 98%;
  margin: 0 auto;
  margin-top: 10px;
}
</style>